<?php
// +----------------------------------------------------------------------
// | OneKeyAdmin [ Believe that you can do better ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://onekeyadmin.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: MUKE <513038996@qq.com>
// +----------------------------------------------------------------------
namespace plugins\alisms\addons;

use app\index\model\Config;
/**
 * 使用阿里云短信
 */
class AliSms 
{
    /**
     * 发送短信
     * @param $templateId string 模板id
     * @param $phoneNumbers number 接收短信的手机号
     * @param $content array 发送的内容格式以["code" => 1234]
     */
    public static function send(string $templateId, $phoneNumbers, $content) 
    {
        $config = Config::getVal('app_alisms');
        if ($config) {
            $domain          = 'dysmsapi.aliyuncs.com';
            $accessKeyId     = $config['accessKeyId'];
            $accessKeySecret = $config['accessKeySecret'];
            $template        = [];
            foreach ($config['template'] as $key => $value) {
                if ($value['id'] === $templateId) {
                    $template = $value;
                }
            }
            if (! empty($template)) {
                // 短信签名，应严格按"签名名称"填写，请参考: https://dysms.console.aliyun.com/dysms.htm#/domestic/text/sign
                $params["SignName"]      = $template['signName'];
                // 短信模板Code，应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/domestic/text/template
                $params["TemplateCode"]  = $template['templateCode'];
                // 短信接收号码
                $params["PhoneNumbers"]  = $phoneNumbers;
                // 短信模板变量对应的实际值
                $params["TemplateParam"] = json_encode($content, JSON_UNESCAPED_UNICODE);
                $res = self::request($accessKeyId, $accessKeySecret, $domain, $params);
                return $res;
            } else {
                return ['status' => 'error', 'message' => '模板id为空'];
            }
        } else {
            return ['status' => 'error', 'message' => '短信未配置'];
        }
    }
    /**
     * 生成签名并发起请求
     *
     * @param $accessKeyId string AccessKeyId (https://ak-console.aliyun.com/)
     * @param $accessKeySecret string AccessKeySecret
     * @param $domain string API接口所在域名
     * @param $params array API具体参数
     * @param $security boolean 使用https
     * @return bool|\stdClass 返回API接口调用结果，当发生错误时返回false
     */
    public static function request($accessKeyId, $accessKeySecret, $domain, $params, $security=false) 
    {
        $params = array_merge($params,[
            "RegionId" => "cn-hangzhou",
            "Action"   => "SendSms",
            "Version"  => "2017-05-25",
        ]);
        $apiParams = array_merge(array (
            "SignatureMethod" => "HMAC-SHA1",
            "SignatureNonce" => uniqid(mt_rand(0,0xffff), true),
            "SignatureVersion" => "1.0",
            "AccessKeyId" => $accessKeyId,
            "Timestamp" => gmdate("Y-m-d\TH:i:s\Z"),
            "Format" => "JSON",
        ), $params);
        ksort($apiParams);
        $sortedQueryStringTmp = "";
        foreach ($apiParams as $key => $value) {
            $sortedQueryStringTmp .= "&" . self::encode($key) . "=" . self::encode($value);
        }
        $stringToSign = "GET&%2F&" . self::encode(substr($sortedQueryStringTmp, 1));
        $sign = base64_encode(hash_hmac("sha1", $stringToSign, $accessKeySecret . "&",true));
        $signature = self::encode($sign);
        $url = ($security ? 'https' : 'http')."://{$domain}/?Signature={$signature}{$sortedQueryStringTmp}";
        $content = self::fetchContent($url);
        $result = json_decode($content, true);
        if ($result['Code'] == 'OK') {
            return ['status' => 'success', 'message' => '发送成功'];
        } else {
            return ['status' => 'error', 'message' => $result['Message']];
        }
    }

    public static function encode($str)
    {
        $res = urlencode($str);
        $res = preg_replace("/\+/", "%20", $res);
        $res = preg_replace("/\*/", "%2A", $res);
        $res = preg_replace("/%7E/", "~", $res);
        return $res;
    }

    public static function fetchContent($url) 
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            "x-sdk-client" => "php/2.0.0"
        ));
        if(substr($url, 0,5) == 'https') {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }
        $rtn = curl_exec($ch);
        if($rtn === false) {
            trigger_error("[CURL_" . curl_errno($ch) . "]: " . curl_error($ch), E_USER_ERROR);
        }
        curl_close($ch);
        return $rtn;
    }
}